import feedparser
from datetime import datetime


class ParseError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return repr(self.msg)



def parse(url):
    d = feedparser.parse(url)
    results = []

    if d.bozo == 1:
        raise ParseError(d.bozo_exception)

    for entry in d.entries:
        link = get_by_keys(entry, ('feedburner_origlink', 'link'))

        date_tuple = get_by_keys(entry, ('date_parsed', 'published_parsed'))
        if (date_tuple):
            published_date = datetime(*date_tuple[0:6])

        if (entry.has_key('content')):
            content = entry['content'][0].value
        else:
            content = get_by_keys(entry, ('description', 'summary'))

        tags = ''
        if (entry.has_key('tags')):
            tags = ','.join([tag.term for tag in entry.tags])
            if tags == 'Uncategorized':
                tags = ''

        title = get_by_keys(entry, ('title',))

        results.append({'link': link,
                'title': title,
                'published_date': published_date,
                'content': content,
                'tags': tags})

    return results


# return first key that found
def get_by_keys(entry, keyList):
    for key in keyList:
        if entry.has_key(key):
            return entry[key]
    return None